# -*- coding: utf-8 -*-
"""
Created on Mon Nov 27 13:12:23 2017

@author: za-xuzhaoye
"""

#from backtest import tdbook,index_long,index_long1,index_short, index_short1
import numpy as np
import pandas as pd
import math
import copy
#import backtest.backtest

OrderedDict={'Profit':np.nan,'AnnualExpR':np.nan,'AnnualVOL':np.nan,
                 'Sharpe':np.nan,'DrawdownMax':np.nan,'Calmar':np.nan,
                 'TradeTimes':np.nan,'AvgHoldPeriod':np.nan}
#%%
def CalTdResultProd(tdbook, index_long, index_short, TAU=365, rate=1.0007e-4, mratio = 1.0, slip=1, unit=100, Cap0=100000.0):
    if len(index_long) == 0:
            d = OrderedDict()
            d['AnnualExpR'] = np.nan
            d['AnnualVOL'] = np.nan
            d['Sharpe'] = np.nan
            d['DrawdownMax'] = np.nan
            d['Calmar'] = np.nan
            d['TradeTimes'] = np.nan
            d['WinningRatio'] = np.nan
            d['AvgWinning'] = np.nan
            d['AvgLosing'] = np.nan
            d['AvgHoldPeriod'] = np.nan
            CalResult = pd.DataFrame(d.items(), columns = ['Parameter', 'Value'])
            CalResult.index=CalResult['Parameter']
            del CalResult['Parameter']
            TradeRecord = pd.DataFrame()
    
    else:
            sgn_hd=tdbook['sgn_hd']    
            pnl = tdbook['prc_long'] + tdbook['prc_short']+tdbook['prc_long1']+tdbook['prc_short1']                   
            turnover = abs(tdbook['prc_long']) + abs(tdbook['prc_short'])    
            commission = turnover * rate                               
    #        slippage = slip * 2 * abs(tdbook['sgn_hd'])                  
    #        pnl_net = pnl - commission - slippage   
    #            tdbook['turnover'] = turnover
    #            tdbook['commission'] = commission
    #        tdbook['slippage'] = slippage
            tdbook['pnl'] = pnl
            size = np.zeros(len(tdbook))                            
            Cap = np.zeros(len(tdbook)) + Cap0                      
            HoldPeriod = np.zeros(len(index_long))                      

#%%
    Captmp = copy.copy(Cap0)
                
    for i in np.arange(len(index_long)):
        sizetmp = np.floor(Captmp /abs(index_long[i])/unit)
        size[index_long[i]:index_short[i]+1] = sizetmp  # 每段交易的手数由现有资金满仓买入计算而得
        Captmp = Captmp + [index_short[i]] * size[index_short[i]] * unit
        if index_short[i]+1 <= len(tdbook):
            Cap[index_short[i]+1:] = Captmp
    #    HoldPeriod[i] = index_short[i] - index_long[i] + 1
            
            HoldPeriod=sgn_hd.count('1',start=0,end=len(sgn_hd))
    
    #%%
    tdbook['commission'] = commission * size * unit
    #        tdbook['slippage'] = slippage * size * unit
    
    AvgHoldPeriod = HoldPeriod.mean()                           # 平均持仓周期
    Capfloat = Cap + pnl * size * unit                      # 实时资金浮动
    Return = np.log(Capfloat / Capfloat.shift(1))               # 收益率
    tdbook['size'] = size
    tdbook['Capital'] = Cap
    tdbook['CapitalFloat'] = Capfloat
    tdbook['Return'] = Return
    
    AnnualExpR = Return.mean() * TAU                            # 年化预期收益
    AnnualVOL = Return.std() * math.sqrt(TAU)                   # 年化波动率
    Sharpe = AnnualExpR/AnnualVOL                               # 夏普比率
    TradeTimes = len()                                    # 交易次数
    tmp = Capfloat / Cap - 1
    TradeResult = tmp[index_short].values                        #每笔交易盈亏比例
    WinningTimes = len(TradeResult[TradeResult>0])
    LosingTimes = len(TradeResult[TradeResult<0])
    WinningRatio = float(WinningTimes) / (float(WinningTimes) + float(LosingTimes))  # 胜率
    AvgWinning = TradeResult[TradeResult>0].mean()
    AvgLosing = TradeResult[TradeResult<0].mean()
    Drawdown = (Capfloat - Capfloat.cummax()) / Capfloat.cummax()   # 回撤
    DrawdownMax = - Drawdown.min()                                # 最大回撤
    Calmar = AnnualExpR / DrawdownMax                           # Calmar比率
    Profit = Capfloat.values[-1]/Cap0 - 1
    tdbook['Drawdown'] = Drawdown
    #%%
    #        StartTime = tdbook['datetime'].iloc[0].strftime('%Y-%m-%d %H:%M:%S')
    #        EndTime = tdbook['datetime'].iloc[-1].strftime('%Y-%m-%d %H:%M:%S')
    StartTime = tdbook['datetime'].iloc[0]
    EndTime = tdbook['datetime'].iloc[-1]        
    d = OrderedDict()
    d['StartTime'] = StartTime
    d['EndTime'] = EndTime
    d['symbol'] = tdbook['symbol'].iloc[0]
    d['Profit'] = Profit
    d['AnnualExpR'] = AnnualExpR
    d['AnnualVOL'] = AnnualVOL
    d['Sharpe'] = Sharpe
    d['DrawdownMax'] = DrawdownMax
    d['Calmar'] = Calmar
    d['TradeTimes'] = TradeTimes
    d['WinningRatio'] = WinningRatio
    d['AvgWinning'] = AvgWinning
    d['AvgLosing'] = AvgLosing
    d['AvgHoldPeriod'] = AvgHoldPeriod
    
    CalResult = pd.DataFrame(d.items(), columns = ['Parameter', 'Value'])
    CalResult.index=CalResult['Parameter']
    del CalResult['Parameter']
    
    TradeRecord=pd.DataFrame()
    TradeRecord['ReturnPerTrade'] = TradeResult
    TradeRecord['HoldPerTrade'] = HoldPeriod
    tdbook.index=tdbook['datetime']
    #            tdbook=tdbook.drop('datetime',axis=1)
    return tdbook, CalResult, TradeRecord
    #    print tdbook
